/**
 * @file connectionCmds.c
 * @author MTF-1
 *
 * @date 14-01-2011 DD-MM-YYYY
 * @version 0.3
 *
 * @section DESCRIPTION
 *
 * Module for connection commands.
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "connectionCmds.h"

#define ERROR 1
#define NOERROR 0

/*Global vars*/
int iSocketFD = 0;

/**
 * Connect to server.
 *
 * @author Rik Janssen, Robbert Busser
 */
int cmdConnect(char *ptr_sIPAdd)
{
    if(iSocketFD) {
        fprintf(stderr, "Error: you are already connected.\n");
        return ERROR;
    }
    else {
        struct sockaddr_in sa;
        iSocketFD = socket(PF_INET, SOCK_STREAM, 0);
        sa.sin_family = AF_INET;
        sa.sin_port = htons(5002);
        inet_aton(ptr_sIPAdd, &(sa.sin_addr));

        if(connect(iSocketFD, (struct sockaddr *)&sa, sizeof sa) < 0) {
            perror("Can't make connection\n");
            close(iSocketFD);
            iSocketFD = 0;
            return ERROR;
        }

        return NOERROR;
    }
}

/**
 * Disconnect current session.
 *
 * @author Rik Janssen
 */
int cmdDisconnect()
{
    if(iSocketFD) {
        printf("Disconnecting...\n");
        close(iSocketFD);
        iSocketFD = 0;
        return NOERROR;
    }
    else {
        fprintf(stderr, "Error: there's no connection to close.\n");
        return ERROR;
    }
}
